package com.lwj.widget.viewpagerindicator_demo.slice;

import com.ms.banner.Log;
import com.ms.banner.Utils;
import com.ms.banner.holder.BannerViewHolder;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.Image;
import ohos.app.Context;
import ohos.global.resource.NotExistException;
import ohos.global.resource.Resource;
import ohos.global.resource.ResourceManager;
import ohos.global.resource.WrongTypeException;
import ohos.media.image.ImageSource;
import ohos.media.image.PixelMap;

import java.io.IOException;

import static ohos.agp.components.ComponentContainer.LayoutConfig.MATCH_PARENT;

/**
 * CustomViewHolder
 *
 * @author name
 * @since 2021-03-20
 */
public class CustomViewHolder implements BannerViewHolder<Object> {
    @Override
    public Component createView(Context context, int position, Object data) {
        Image image1 = new Image(context);
        image1.setScaleMode(Image.ScaleMode.STRETCH);
        image1.setLayoutConfig(new ComponentContainer.LayoutConfig(MATCH_PARENT, MATCH_PARENT));
        if (data instanceof String) {
            Utils.getInstance().setBitmap(context, image1, (String) data);
            return image1;
        }
        try {
            ImageSource.SourceOptions options = new ImageSource.SourceOptions();
            options.formatHint = "image/jpg";
            ImageSource.DecodingOptions decodingOptions = new ImageSource.DecodingOptions();
            ResourceManager manager = context.getResourceManager();
            String path = manager.getMediaPath((Integer) data);
            Resource r1 = manager.getRawFileEntry(path).openRawFile();
            ImageSource source = ImageSource.create(r1, options);
            PixelMap p1 = source.createPixelmap(decodingOptions);
            image1.setPixelMap(p1);
        } catch (IOException e) {
            Log.e("banner IOException :", e.getMessage());
        } catch (NotExistException e) {
            Log.e("banner NotExistException:", e.getMessage());
        } catch (WrongTypeException e) {
            Log.e("banner WrongTypeException:", e.getMessage());
        }
        return image1;
    }
}
